/**
 *  北京中流科技有限责任公司   版权所有
 */
package cn.com.chinasoa.portlet.dao.toy.util;

import java.util.Properties;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

import cn.com.chinasoa.portlet.dao.toy.Toy;

/**
 * @author 刘洋(liuyang@chinasoa.com.cn)
 * 2006-12-17 下午11:05:53
 */
public class HibernateHelper {
	public static SessionFactory sessionFactory;
	public static Properties cfgProperties = new Properties();
	static{
		try {
			cfgProperties.load(HibernateHelper.class.getResourceAsStream("hibernate.properties"));
			Configuration cfg = new Configuration();
			cfg.addProperties(cfgProperties);
			cfg.addClass(Toy.class);		
			sessionFactory = cfg.buildSessionFactory();			
		} catch (Exception e1) {
			e1.printStackTrace();
		}
	}

	public static final ThreadLocal session = new ThreadLocal();

	public static Session currentSession() throws HibernateException {
		Session s = (Session) session.get();
	    if (s == null) {
	    	s = sessionFactory.openSession();
	    	session.set(s);
	    }
	    return s;
	}

	public static void closeSession() throws HibernateException {
		Session s = (Session) session.get();
	    if (s != null)s.close();
	    session.set(null);
	}
}
